//
//  DataBaseBoxImageModel.m
//  WuliHanhan
//
//  Created by tang on 16/3/17.
//  Copyright © 2016年 LVpeng. All rights reserved.
//

#import "DataBaseBoxImageModel.h"
#import "FMDB.h"
#import "Header.h"
@interface DataBaseBoxImageModel ()
{
    FMDatabase *db;
    //    NSString *fileString;
    
}

@end

@implementation DataBaseBoxImageModel


sloganIntence(DataBaseBoxImageModel);



//打开数据库
- (void)openDataBase
{
    
    //创建编辑图片数据库
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    //    NSLog(@"%@", documentDirectory);
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"MyDatabase.db"];
    db = [FMDatabase databaseWithPath:dbPath] ;
    if (![db open]) {
        NSLog(@"Could not open db");
        //        return ;
    }
    else
    {
//        [db executeUpdate:@"DROP TABLE IF EXISTS DownLoadImage"];
        [db executeUpdate:@"CREATE TABLE IF NOT EXISTS DownLoadImage (ImageData blob, CellID integer, selectID integer)"];
    }
    
}



//存储图片
- (void)writeImageWithConnectID:(NSString *)IDString withImageData:(NSData *)imageData
{
    BOOL writeIsOK = [db executeUpdate:@"INSERT INTO DownLoadImage (ImageData, CellID) VALUES (?,?)", imageData, IDString];
    
    if (writeIsOK)
    {
        NSLog(@"添加成功");
    }
    else
    {
        NSLog(@"添加失败");
    }

}



//读取图片
- (void)readDownLoadImage:(getImageCallBack)callBack
{
    NSMutableArray *array = [NSMutableArray new];
    NSMutableArray *dataArray = [NSMutableArray new];
    
    FMResultSet *rs = [db executeQuery:@"SELECT CellID , ImageData FROM DownLoadImage"];
    
    //    NSLog(@"%@", rs);
    
    while ([rs next]) {
        NSString *name = [rs stringForColumn:@"CellID"];
        [array addObject:name];
        //        NSLog(@"")
        NSData *data = [rs dataForColumn:@"ImageData"];
        [dataArray addObject:data];
    }
    
    //    NSLog(@"da%@", nameAY);
    callBack(array, dataArray);

}




//读取图片ID
- (void)readDownLoadImageID:(getImageCallID)callBack
{
    NSMutableArray *array = [NSMutableArray new];
//    NSMutableArray *dataArray = [NSMutableArray new];
    
    FMResultSet *rs = [db executeQuery:@"SELECT CellID FROM DownLoadImage"];
    
    
    while ([rs next]) {
        NSString *name = [rs stringForColumn:@"CellID"];
        [array addObject:name];
        //        NSLog(@"")
//        NSData *data = [rs dataForColumn:@"ImageData"];
//        [dataArray addObject:data];
    }
    
    //    NSLog(@"da%@", nameAY);
    callBack(array);
    
}


////写入图片id
//- (void)writeCellIndex:(NSString *)string
//{
//    BOOL writeIsOK = [db executeUpdate:@"INSERT INTO DownLoadImage (ImageData, CellID) VALUES (?,?)", imageData, IDString];
//    
//    if (writeIsOK)
//    {
//        NSLog(@"添加成功");
//    }
//    else
//    {
//        NSLog(@"添加失败");
//    }
//
//}

@end
